<script setup lang="tsx">
import { Popconfirm, Tag } from 'ant-design-vue';
import { ref } from 'vue';
import { fetchBatchDeleteRoles, fetchDeleteRole, fetchGetRoleList } from '@/service/api';
import { useTable, useTableOperate, useTableScroll } from '@/hooks/common/table';
import { $t } from '@/locales';
import { enableStatusRecord } from '@/constants/business';
// import { useAuth } from '@/hooks/business/auth';
import AuthButton from '@/components/common/auth-button.vue';
import RoleOperateDrawer from './modules/role-operate-drawer.vue';
import RoleViewDrawer from './modules/role-view-drawer.vue';
import RoleSearch from './modules/role-search.vue';
const { tableWrapperRef, scrollConfig } = useTableScroll();
// const { hasAuthSync } = useAuth();

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetRoleList,
  apiParams: {
    current: 1,
    size: 10,
    status: undefined,
    roleName: undefined,
    roleCode: undefined
  },
  columns: () => [
    {
      key: 'index',
      dataIndex: 'index',
      title: $t('common.index'),
      width: 64,
      align: 'center'
    },
    {
      key: 'roleName',
      dataIndex: 'roleName',
      title: $t('page.manage.role.roleName'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'roleCode',
      dataIndex: 'roleCode',
      title: $t('page.manage.role.roleCode'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'roleDesc',
      dataIndex: 'roleDesc',
      title: $t('page.manage.role.roleDesc'),
      minWidth: 120
    },
    {
      key: 'status',
      dataIndex: 'status',
      title: $t('page.manage.role.roleStatus'),
      align: 'center',
      width: 100,
      customRender: ({ record }) => {
        if (record.status === null) {
          return null;
        }

        const tagMap: Record<Api.Common.EnableStatus, string> = {
          1: 'success',
          2: 'warning'
        };

        const label = $t(enableStatusRecord[record.status]);

        return <Tag color={tagMap[record.status]}>{label}</Tag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center' as const,
      width: 180,
      customRender: ({ record }: { record: any }) => (
        <div class="flex-center gap-8px">
          <AuthButton permission="ROLE_VIEW" onClick={() => handleView(record)} type="primary" ghost size="small">
            {$t('common.view')}
          </AuthButton>
          <AuthButton permission="ROLE_EDIT" onClick={() => edit(record.id)} type="primary" ghost size="small">
            {$t('common.edit')}
          </AuthButton>
          <Popconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id)}>
            <AuthButton permission="ROLE_DELETE" danger size="small">
              {$t('common.delete')}
            </AuthButton>
          </Popconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  rowSelection,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

// 查看功能状态
const viewDrawerVisible = ref(false);
const viewingData = ref<Api.SystemManage.Role | null>(null);

async function handleBatchDelete() {
  try {
    await fetchBatchDeleteRoles(checkedRowKeys.value.map(id => Number(id)));
    onBatchDeleted();
  } catch {
    window.$message?.error('操作失败');
  }
}

async function handleDelete(id: number) {
  try {
    await fetchDeleteRole(id);
    onDeleted();
  } catch {
    window.$message?.error('操作失败');
  }
}

function edit(id: number) {
  handleEdit(id);
}

// 查看角色详情
function handleView(record: Api.SystemManage.Role) {
  viewingData.value = record;
  viewDrawerVisible.value = true;
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <RoleSearch
      v-model:model="searchParams"
      @reset="
        () => {
          resetSearchParams();
          getDataByPage();
        }
      "
      @search="getDataByPage"
    />
    <ACard
      :title="$t('page.manage.role.title')"
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          add-permission="ROLE_ADD"
          delete-permission="ROLE_DELETE"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <ATable
        ref="tableWrapperRef"
        :columns="columns"
        :data-source="data"
        :row-selection="rowSelection"
        :loading="loading"
        row-key="id"
        size="small"
        :pagination="mobilePagination"
        :scroll="scrollConfig"
        class="h-full"
      />
      <RoleOperateDrawer
        v-model:open="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />

      <!-- 查看角色详情抽屉 -->
      <RoleViewDrawer v-model:model-value="viewDrawerVisible" title="查看角色详情" :width="600">
        <div v-if="viewingData" class="role-view-content">
          <ARow :gutter="16">
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">角色名称：</label>
                <span class="info-value">{{ viewingData.roleName }}</span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">角色编码：</label>
                <span class="info-value">{{ viewingData.roleCode }}</span>
              </div>
            </ACol>
            <ACol :span="24">
              <div class="info-item">
                <label class="info-label">角色描述：</label>
                <span class="info-value">{{ viewingData.roleDesc || '-' }}</span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">状态：</label>
                <span class="info-value">
                  <ATag v-if="viewingData.status" :color="Number(viewingData.status) === 1 ? 'success' : 'warning'">
                    {{ Number(viewingData.status) === 1 ? '启用' : '禁用' }}
                  </ATag>
                  <span v-else>-</span>
                </span>
              </div>
            </ACol>
          </ARow>
        </div>
      </RoleViewDrawer>
    </ACard>
  </div>
</template>

<style scoped>
.role-view-content {
  padding: 16px 0;
}

.info-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.info-label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  margin-right: 8px;
}

.info-value {
  color: #333;
  flex: 1;
}
</style>

<style scoped></style>
